package com.engineering.elink.service.impl;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.engineering.elink.domain.Video;
import com.engineering.elink.domain.VideoSubtitle;
import com.engineering.elink.service.VideoSubTitleService;
import com.engineering.elink.videodao.VideoMapper;
import com.engineering.elink.videodao.VideoSubtitleMapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.zxy.core.enums.ErrorType;
import com.zxy.core.util.CollectionUtil;
import com.zxy.core.util.JsonBinderUtil;
import com.zxy.core.util.ResJsonUtil;

@Service
public class VideoSubTitleServiceImpl implements VideoSubTitleService{

	@Autowired
	private VideoSubtitleMapper videoSubtitleMapper;
	
	@Autowired
	private VideoMapper videoMapper;
	
	@Override
	public Map<String, Object> add(String jsonStr) {
		
		List<VideoSubtitle> vsList=JsonBinderUtil.fromJsontolist(jsonStr,new TypeReference<List<VideoSubtitle>>(){});
		if(CollectionUtil.collectionIsEmpty(vsList)){
			return ResJsonUtil.getMap(ErrorType.REQUEST_PARAMS_ERROR);
		}
		
		Video video=null;
		VideoSubtitle vs=null;
		for(VideoSubtitle vsub:vsList){
			if(vsub==null)continue;
			
			video=this.videoMapper.selectByPrimaryKey(vsub.getVideoId());
			if(video==null){
				return ResJsonUtil.getMap(ErrorType.VIDEO_ERROR);
			}
			
			vs=videoSubtitleMapper.selectByVideoId(vsub.getVideoId(), vsub.getType());
			if(vs==null){
				vs=new VideoSubtitle();
				vs.setVideoId(vsub.getVideoId());
				vs.setType(vsub.getType());
				vs.setAddress(vsub.getAddress());
				videoSubtitleMapper.insertSelective(vs);
			}else{
				vs.setAddress(vsub.getAddress());
				videoSubtitleMapper.updateByPrimaryKeySelective(vs);
			}
			
		}
		
		return ResJsonUtil.getMap(ErrorType.SUCCESS);
	}

}
